<?php

namespace App\Repositories\Eloquent\Act;

use Illuminate\Container\Container as App;
use App\Repositories\Eloquent\Repository;
use Ramsey\Uuid\Uuid;
use DB;

use App\Repositories\Eloquent\Act\JoinRepository as Join;
use App\Repositories\Eloquent\Act\QuestionRepository as Question;
use App\Repositories\Eloquent\Act\AnswerRepository as Answer;

class TopicRepository extends Repository
{

    /**
     * @param App
     */

    protected $question,$join, $answer;

    protected $debug;

    public function __construct(App $app, Question $question, Join $join, Answer $answer)
    {
        parent::__construct($app);

        $this->join = $join;

        $this->question = $question;

        $this->answer = $answer;

        $this->debug = env('SMS_DEBUG');
    }

    /**
     * 指定模型名称
     *
     * @return mixed
     */
    function model()
    {
        return 'App\Models\Act\Topic';
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $result = $this->model
                ->withCount('joins','questions')
                ->orderBy('id', 'asc');

        return $result;
    }


    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store($request)
    {
        $topic = $this->create([
            'name'      => $request->name,
            'type'  => is_null($request->type) ? 1:$request->type,
            'status'    => is_null($request->status) ? 0:$request->status,
            'desc'      => $request->desc,
            'token'     => Uuid::uuid4()->toString(),
        ]);

        if (!!$topic) {
             return $this->responseSuccess('增加专题活动成功', $topic, route('act.index'));
        }

        return $this->responseFail(500,'增加专题活动失败');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        $topic = $this->model->find($id);

        if (!$topic)
            return $this->responseFail(404, '活动信息不正确');

        return $topic;
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function renew($request, $id)
    {
        $result = $this->update([
            'name'      => $request->name,
            'type'    => is_null($request->type) ? 1:$request->type,
            'status'      => is_null($request->status) ? 0:$request->status,
            'desc'      => $request->desc,
        ], $id);
        
        if (!!$result) {
             return $this->responseSuccess('修改答题活动成功');
        }

        return $this->responseFail(500,'修改答题活动失败');
    }


    public function byUuid($uuid)
    {
        $topic = $this->findBy('token',$uuid);
        
        if (!$topic)
            return $this->responseFail(404, '活动信息不正确');

        return $topic;
    }


    public function answer($request)
    {
        
        if( $this->join->isAttend( $request) )
            return $this->responseFail(405, '您已经参加过答题活动！');


        if(!$this->debug){
            if($request->smscode != \Session::get('smscode'))
                return $this->responseFail(405, '验证码不正确！');
        }        

        //检测题目状态
        $question = $this->question->find($request->question_id);
           //$c = $this->question->corrects($request);
        if(!!$question && $question->status !== STATUS_NORMAL)
            return $this->responseFail(405, '该题已被他人作答！');
        
        //验证答案
        if(!!$question->ischeck == STATUS_NORMAL){
           if(!$this->checkAnswer($question,$request->answer)){
                return $this->responseFail(405, '回答不正确</br>请重新作答或选择其它题目');
           }
        } 
            

        DB::beginTransaction();
        try{
            //答题用户
            $user = $this->join->create([
                'name'      => $request->name,
                'mobile'       => $request->mobile,
                'topic_id'   => $request->topic_id,
            ]);            
            
            //记录用户答题详情
            if(!!$user){
                
                $answer = $request->answer;
                //选择题回答选项转换
                if($question->type == QUESTION_SELECT)
                    $answer = implode(',',$answer);

                $this->answer->create([
                    'join_id'=>$user->id,
                    'topic_id'=>$request->topic_id,
                    'question_id'=>$request->question_id,
                    'answer'=>$answer,
                ]);     
            }
            //题目标记为已答
            $this->question->update([
                'status' => CODE_UNAUTHORIZE,
            ], $request->question_id);

            DB::commit();

            return $this->responseSuccess('答题成功！', null, route('wx.act.topic',$request->uuid));

        } catch (Exception $e) {

            DB::rollback();

            return $this->responseFail(500,'答题失败！');
        }

    }

    //答案检测
    protected function checkAnswer($question,$answer)
    {
        //填空题
        if($question->type == QUESTION_BLANK){
            $correct = $question->options()->first()->content;
            if(strcmp($answer,$correct ) == 0 )
                return true;
        }

        //选择题
        if($question->type == QUESTION_SELECT){
            
            $answer = array_values($answer);            
            $correct = $question->corrects()->pluck('id')->toArray();
            //先判断选项数是否正确
            if(count($answer) !== count($correct))                    
                return false;
            //选项数相等，则判断差集
            $diff = array_diff($correct, $answer);                
            if(count($diff) == 0)
                return true;
           
        }

        return false;
    }


}